<template>
  <div class="page-container">

    <div v-if=" activeName == 'second'">
      <h2>你好！XXXX</h2>
      <div>您收到来自{{inviteInfo.enterpriseName}}的邀请。加入该企业，即可与企业同事开启高效协作</div>
      <el-button type="primary" size="small" @click="acceptInvite">同意</el-button>

      <el-button type="info" size="small" @click="refuseInvite">拒绝</el-button>
    </div>



    <div v-if=" activeName == 'third'">
      <h2>加入成功</h2>
      <div>您已成功加入{{inviteInfo.enterpriseName}}.进入企业，与同事开启高效协作</div>
      <div><el-button type="primary" @click="switchNewEnterprise">切换至新企业</el-button></div>
    </div>

    <el-empty v-if=" activeName == 'fouth'" description="邀请码已过期">
    <el-button type="primary" size="small" @click="goBack">返回</el-button>
  </el-empty>
  </div>
</template>

<script>
import {reactive, toRefs, onMounted,ref,computed} from 'vue'
import {useRoute,useRouter} from 'vue-router'
import { ElMessage } from 'element-plus'
import {getInviteInfoVo} from "/@/api/sys/dept"
import { getCode, registerLogin, setEnterprise } from '/@/api/login';
import { Session,Local } from '/@/utils/storage'
import Cookies from 'js-cookie'
import { useThemeConfig } from '/@/stores/themeConfig'
import { initFrontEndControlRoutes } from '/@/router/frontEnd'
import { initBackEndControlRoutes } from '/@/router/backEnd'
import { storeToRefs } from 'pinia'
import { formatAxis } from '/@/utils/formatTime'
import { NextLoading } from '/@/utils/loading'
import { useI18n } from 'vue-i18n'
import { createUserByShop,isJoinDept } from '/@/api/sys/user';
import { get,update } from '/@/api/sys/message'
export default {
  name: "invite",
  setup() {
    const route = useRoute()
    const router = useRouter()
    const  ruleFormRef = ref()
    const storesThemeConfig = useThemeConfig()
    const { themeConfig } = storeToRefs(storesThemeConfig)
    const { t } = useI18n()
    const state = reactive({
      isNorRegister: false,
      formSize: 'small',
      ruleForm: {
        name: '',
        phone: '',
        code:''
      },
      rules:{
        name: [
          { required: true, message: '请输入您的姓名', trigger: 'blur' },
          { min: 2, max: 64, message: '最少需要两个汉字', trigger: 'blur' },
        ],
        phone:[
          {
            required: true,
            message: "手机号不能为空",
            trigger: "blur",
          },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur",
          },
        ],
        code:[ {
          required: true,
          message: "请输入验证码",
          trigger: "blur",
        },]
      },
      activeName: 'second',
      inviteInfo:{},
      butDisable:false,
      butText: '获取验证码',
      butTime: 3,
      loginSuccessInfo:{},
      sendData:{}
    })




    const joinSuccessCountdown = () => {
      let time = 3
      const interver = setInterval(() => {
        time--
        if (time <= 0) {
          state.butTime = 0
          clearInterval(interver)
          router.push({
            path: '/login'
          })
        } else {
          state.butTime = time
        }
      }, 1000)
    }

    const switchNewEnterprise = () => {
      let data = state.loginSuccessInfo
      // 存储 token 到浏览器缓存
      Cookies.set('enterpriseName', state.inviteInfo.enterpriseName)
      setEnterprise(state.inviteInfo.enterpriseId).then(res=>{
        if(res.code == 0){
          // 登录成功 初始化
          // proxy.initialize()
          // TODO 获取路由菜单.....
          // 模拟数据，对接接口时，记得删除多余代码及对应依赖的引入。用于 `/src/stores/userInfo.ts` 中不同用户登录判断（模拟数据）
          if (!themeConfig.value.isRequestRoutes) {
            // 前端控制路由，2、请注意执行顺序
            initFrontEndControlRoutes()
            signInSuccess()
          } else {
            // 模拟后端控制路由，isRequestRoutes 为 true，则开启后端控制路由
            // 添加完动态路由，再进行 router 跳转，否则可能报错 No match found for location with path "/"
            initBackEndControlRoutes()
            // 执行完 initBackEndControlRoutes，再执行 signInSuccess
            signInSuccess()
          }
        }
      })
    }
    const signInSuccess = () => {
      // 初始化登录成功时间问候语
      let currentTimeInfo = currentTime.value
      router.push('/')
      // 登录成功提示
      ElMessage.success("切换成功")
      // 添加 loading，防止第一次进入界面时出现短暂空白
      NextLoading.start()
    }

    // 时间获取
    const currentTime = computed(() => {
      return formatAxis(new Date())
    })

    const goBack = () => { 
      router.push('/')
    }
    
    const acceptInvite = () => { 
        createUserByShop(state.sendData).then(res=>{
            if(res.code == 0){
              state.activeName = 'second'
            }
        })
    }
    const refuseInvite = () => { 
      ElMessage.error('拒绝邀请后删除信息!待定接口')
    }

    onMounted(() => {
      if (route.query.infoId) {
        state.isNorRegister = true
        getInviteInfoVo({infoId:route.query.infoId}).then(res=>{
          state.inviteInfo = res.data
          console.log(state.inviteInfo)
          if(res.code == 0){
            //首次判断是否已经操作加入过
            state.sendData = {
                userId:Cookies.get('userId'),
                enterpriseId:state.inviteInfo.enterpriseId,
                userName:Cookies.get('userName'),
                type: 0,
                isJoin:0,
                deptId:state.inviteInfo.deptId
              }
            isJoinDept(state.sendData).then(result=>{
                if(result.code == 0){
                  state.activeName = result.data == 'yes'?'second':'third'
                }
            })
            
          }
        })
      } else {
        state.isNorRegister = false
        state.activeName = 'fouth'
      }
    })


    return {
      ...toRefs(state),
      ruleFormRef,
      joinSuccessCountdown,
      switchNewEnterprise,
      currentTime,
      signInSuccess,
      goBack,
      acceptInvite
    }
  }
}
</script>

<style lang="scss" scoped>
.page-container {
  margin: 0 auto;
  width: 400px;
  .rule-form{
    margin-top: 200px;
  }
}
</style>

